<?php

namespace App\Exports;

use App\Models\Balance;
use App\Models\Buy;
use App\Models\Sell;
use Carbon\Carbon;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\FromCollection;
// use PhpOffice\PhpSpreadsheet\Shared\Date;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;

class ReportExport implements FromCollection, WithHeadings
{
  public function collection()
  {
    $buys = Buy::where('seller_id', sellerId())
      ->thisMonth()
      ->latest()
      ->get();
    $sells = Sell::where('seller_id', sellerId())
      ->thisMonth()
      ->latest()
      ->get();

    $group = $buys->merge($sells)->groupBy(function ($item) {
      return $item->updated_at->format('Y-m-d');
    });

    $list = [];
    foreach ($group as $key => $rows) {
      $buy = 0;
      $sell = 0;
      $fee = 0;
      $tip = 0;
      $done_count = 0;
      $undone_count = 0;
      $done_coins = 0;
      $undone_coins = 0;

      foreach ($rows as  $row) {
        if ($row instanceof Buy) { // buy
          if ($row->state === 'unfreeze') {
            $buy -= $row->coins;
          }
          $fee = 1 * bcadd($fee, $row->seller_fee, 3);
          $tip = 1 * bcadd($tip, $row->seller_tip, 3);
        } else {
          $sell += $row->coins;
        }
        if (in_array($row->state, ['took', 'waiting'])) {
          $undone_count++;
          $undone_coins += $row->coins;
        } else {
          $done_count++;
          $done_coins += $row->coins;
        }
      }
      $list[] = [
        'date' => $key,
        'sell' => $sell,
        'buy' => $buy,
        'fee' => $fee,
        'tip' => $tip,
        'done_coins' => $done_coins,
        'done_count' => $done_count,
        'undone_coins' => $undone_coins,
        'undone_count' => $undone_count,
      ];
    }

    return collect($list);
  }

  public function headings(): array
  {
    return [
      '日期',
      '买币+',
      '卖币-',
      '手续费',
      '支出奖励',
      '已处理',
      '已处理笔数',
      '未处理',
      '未处理笔数',
    ];
  }

  // public function map($balance): array
  // {
  //   return [
  //     $balance->id,
  //     $balance->type,
  //     $balance->value,
  //     $balance->b4,
  //     $balance->after,
  //     $balance->created_at->format('Y-m-d H:i'),
  //     $balance->order_id . ' '
  //   ];
  // }
}
